<template>
  <view class="container pageBg">
    <!-- 对话历史 -->
    <scroll-view class="chat-container" scroll-y>
      <!-- 系统欢迎语 -->
      <view class="message ai">
        <view class="avatar">🤖</view>
        <view class="content">
          <text class="system-text">我是DeepSeek的家庭养老AI助手，基于先进的R1模型，为您提供专业的健康咨询和生活指导。您可以问我以下问题：</text>
          <view class="common-questions">
            <text 
              v-for="(q, index) in commonQuestions" 
              :key="index"
              class="question-tag"
              @click="sendQuestion(q)"
            >
              {{ q }}
            </text>
          </view>
        </view>
      </view>

      <!-- 历史消息 -->
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="['message', msg.isAI ? 'ai' : 'user']"
      >
        <view class="avatar">{{ msg.isAI ? '🤖' : '👤' }}</view>
        <view class="content">
          <text class="text">{{ msg.content }}</text>
          <text class="time">{{ formatTime(msg.timestamp) }}</text>
        </view>
      </view>

      <!-- 思考中状态 -->
      <view v-if="isThinking" class="message ai">
        <view class="avatar">🤖</view>
        <view class="content">
          <text class="thinking-text">DeepSeek正在思考中...</text>
          <view class="loading-dots">
            <text class="dot">.</text>
            <text class="dot">.</text>
            <text class="dot">.</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <input
        v-model="inputText"
        placeholder="输入您的问题"
        @confirm="sendMessage"
        class="input"
      />
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

// API配置
const API_CONFIG = {
  baseURL: 'https://ai.synnovator.com:9443/v1',
  apiKey: 'sk-kgmxAkUgYCieVY9r233b4aBdBb7642F398A02fEe5e92Bf8c',
  model: 'DeepSeek-R1-0528'
}

// 常见问题列表
const commonQuestions = ref([
  '你好',
  '你会做什么',
  '糖尿病老人能吃哪些水果？',
  '突然心慌气短该怎么做？',
  '总记不住吃药时间怎么办？'
])

// 对话数据
const messages = ref([])
const inputText = ref('')
const isThinking = ref(false)

// 发送消息到DeepSeek API
const sendMessage = async () => {
  if (!inputText.value.trim()) return

  // 添加用户消息
  addUserMessage(inputText.value)
  
  // 显示思考状态
  isThinking.value = true
  
  try {
    // 构建对话历史
    const conversationHistory = messages.value.map(msg => ({
      role: msg.isAI ? 'assistant' : 'user',
      content: msg.content
    }))
    
    // 调用DeepSeek API
    const response = await callDeepSeekAPI(conversationHistory)
    
    // 添加AI回复
    addAIMessage(response)
    
  } catch (error) {
    console.error('API调用失败:', error)
    addAIMessage('抱歉，我现在无法回答您的问题，请稍后再试。')
  } finally {
    // 重置状态
    inputText.value = ''
    isThinking.value = false
  }
}

// 调用DeepSeek API
const callDeepSeekAPI = async (conversationHistory) => {
  const requestData = {
    model: API_CONFIG.model,
    messages: [
      {
        role: 'system',
        content: '你是DeepSeek的家庭养老AI助手，专门为老年人提供健康咨询、生活指导和紧急帮助。请用温和、耐心的语气回答用户的问题，并提供实用的建议。'
      },
      ...conversationHistory
    ],
    temperature: 0.7,
    max_tokens: 1000,
    stream: false
  }

  const response = await uni.request({
    url: `${API_CONFIG.baseURL}/chat/completions`,
    method: 'POST',
    header: {
      'Authorization': `Bearer ${API_CONFIG.apiKey}`,
      'Content-Type': 'application/json'
    },
    data: requestData
  })

  if (response.data && response.data.choices && response.data.choices.length > 0) {
    return response.data.choices[0].message.content
  } else {
    throw new Error('API响应格式错误')
  }
}

// 添加用户消息
const addUserMessage = (text) => {
  messages.value.push({
    content: text,
    isAI: false,
    timestamp: new Date()
  })
}

// 添加AI消息
const addAIMessage = (text) => {
  messages.value.push({
    content: text,
    isAI: true,
    timestamp: new Date()
  })
}

// 点击预设问题
const sendQuestion = (q) => {
  inputText.value = q
  sendMessage()
}

// 时间格式化
const formatTime = (date) => {
  return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}
</script>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-container {
  flex: 1;
  padding: 20rpx;
}

.message {
  display: flex;
  margin-bottom: 30rpx;
}

.message.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  margin: 0 20rpx;
}

.content {
  max-width: 70%;
  padding: 20rpx;
  border-radius: 12rpx;
  position: relative;
}

.message.ai .content {
  background: #fff;
}

.message.user .content {
  background: #007AFF;
  color: white;
}

.text {
  font-size: 28rpx;
  line-height: 1.6;
}

.time {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.input-area {
  display: flex;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
}

.input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.send-btn {
  background: #007AFF;
  color: white;
  width: 140rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
}

.common-questions {
  margin-top: 20rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.question-tag {
  display: inline-block;
  padding: 10rpx 20rpx;
  background: #f0f0f0;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
}

.system-text {
  color: #666;
  font-size: 28rpx;
}

.thinking-text {
  color: #999;
  font-style: italic;
}

.loading-dots {
  display: flex;
  margin-top: 10rpx;
}

.dot {
  color: #007AFF;
  font-size: 32rpx;
  animation: blink 1.4s infinite;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes blink {
  0%, 80%, 100% {
    opacity: 0;
  }
  40% {
    opacity: 1;
  }
}
</style>